package com.supermap.chaincode;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperledger.fabric.shim.ChaincodeBase;
import org.hyperledger.fabric.shim.ChaincodeStub;
import org.hyperledger.fabric.shim.ResponseUtils;

import java.lang.reflect.Field;
import java.nio.charset.Charset;

public class SupermapCC extends ChaincodeBase {

    private static Log _logger = LogFactory.getLog(SupermapCC.class);

    public static void main(String[] args) {
//        _logger.info("OpenSSL avaliable: " + OpenSsl.isAvailable());
        System.setProperty("file.encoding","UTF-8");
        try {
            Field charset = Charset.class.getDeclaredField("defaultCharset");
            charset.setAccessible(true);
            charset.set(null, null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        new SupermapCC().start(args);
    }

    @Override
    public Response init(ChaincodeStub stub) {
        return ResponseUtils.newSuccessResponse();
    }

    @Override
    public Response invoke(ChaincodeStub stub) {
        try {
            _logger.info("Invoke java supermap chaincode");
            String func = stub.getFunction();

            if (func.equals("Put")) {
                return put(stub);
            }
            if (func.equals("Get")) {
                return get(stub);
            }
            return ResponseUtils.newErrorResponse("Invalid invoke function name.");
        } catch (Throwable e) {
            return ResponseUtils.newErrorResponse(e);
        }
    }

    private Response put(ChaincodeStub stub){

        String str = String.valueOf(Math.random());
        stub.putStringState("key"+str, "value"+str);

        String returnMessage = "execute chaincode successfully";
        return ResponseUtils.newSuccessResponse(returnMessage);

    }

    private Response get(ChaincodeStub stub) {
        String str = String.valueOf(Math.random());
        byte[] state = stub.getState("key" + str);

        String returnMessage = "execute chaincode successfully";
        return ResponseUtils.newSuccessResponse(returnMessage, state);

    }
}
